package com.feiyun.util;

import com.feiyun.exception.ExceptionTypeEnum;
import com.feiyun.exception.ServiceException;
import org.apache.commons.io.FilenameUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;

/**
 * Function Desc: FileUtil
 *
 * @author yan
 * @since 2023/3/28 22:23
 */
public class FileUtil {
    private static final List<String> ALLOWED_PICTURE_EXTENSIONS = Arrays.asList("jpg", "jpeg", "png");

    /**
     * 文件上传
     *
     * @param file 用户上传的头像或者照片
     */
    public static void validateFile(MultipartFile file) {
        // 校验后缀
        if (isAllowedFileExtension(file.getOriginalFilename())) {
            throw new ServiceException(
                    ExceptionTypeEnum.FILE_EXCEPTION_TYPE);
        }
        // 大文件限制10M
        if (file.getSize() >= 1024 * 1024 * 10) {
            throw new ServiceException(
                    ExceptionTypeEnum.FILE_EXCEPTION_TYPE);
        }
    }

    private static boolean isAllowedFileExtension(String fileName) {
        String suffix = FilenameUtils.getExtension(fileName);
        return !ALLOWED_PICTURE_EXTENSIONS.contains(suffix);
    }

    /**
     * 给上传的照片弄个新名字
     *
     * @param file 照片
     * @return New File Name
     */
    public static String convertNewFileName(MultipartFile file) {
        String filename = file.getOriginalFilename();
        String newName = LocalDateTime.now()
                .atZone(ZoneId.systemDefault())
                .format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
        return newName + "." + FilenameUtils.getExtension(filename);
    }

}
